<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        table {
            width: 800px;
            border: 1px solid #ccc;
            border-collapse: collapse;
            margin: 30px 0;
        }

        th,
        td {
            padding: 5px 10px;
            text-align: left;
            border: 1px solid #ccc;
        }
    </style>
    <script src="./tools/axios.js"></script>
</head>

<body>
    <h3> 展示所有的用户数据 </h3>

    <table>
        <thead>
            <tr>
                <!-- <th>用户id</th> -->
                <th>用户名称</th>
                <th>用户性别</th>
                <th>用户年龄</th>
                <th>联系方式</th>
                <th>地址</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <script>

        // 初始化数据
        ; (async function () {
            // 发请求
            const res = await axios({
                url: 'http://127.0.0.1:3000/users'
            })

            // console.log(res);
            const { data } = res.data
            let str = ''
            data.forEach(item => {
                str += `
                <tr>
                    <td>${item.name}</td>
                    <td>${item.gender}</td>
                    <td>${item.age}</td>
                    <td>${item.tel}</td>
                    <td>${item.addr}</td>
                    <td>
                        <button id="${item._id}">编辑</button>
                        <button id="${item._id}">删除</button>
                    </td>
                </tr>
                `
            })

            document.querySelector('tbody').innerHTML = str;
        })();


        // 给编辑按钮注册事件
        document.querySelector('tbody').onclick = async function (e) {
            if (e.target.nodeName === 'BUTTON') {
                // 编辑
                if (e.target.textContent === '编辑') {
                    // 获取自身的id
                    const id = e.target.id;
                    location.href = './05-修改用户数据.html?id=' + id
                }

                // 删除
                if (e.target.textContent === '删除') {
                    const id = e.target.id;

                    const result = confirm('是否确定删除？');
                    if (result) {
                        const res = await axios({
                            methods: 'delete',
                            url: 'http://127.0.0.1:3000/users/' + id
                        })

                        if (res.status === 200) {
                            alert(res.data.msg)

                            // 会刷新页面
                            location.reload();
                        }
                    }
                }
            }
        }

    </script>
</body>

</html>